<template>
    <div @click="click" class="video-upload">
        <slot></slot>
        <input type="file" ref="file" @change="onChange"
               :accept="accept"
               :disabled="disabled">
        <el-progress :percentage="percentage" v-if="uploading"></el-progress>
    </div>
</template>

<script>
import { Progress } from 'element-ui';
import VideoUpload from '@/helpers/VideoUpload';

export default {
    components: {
        ElProgress: Progress,
    },
    props: ['accept', 'disabled', 'value'],
    data() {
        return {
            params: {},
            percentage: 0,
            uploading: false,
        };
    },
    methods: {
        onChange(e) {
            const observer = {
                next: (res) => { // 上传中
                    this.uploading = true;
                    this.percentage = Math.floor(res.total.percent);
                    this.$emit('next', res);
                },
                error: (err) => { // 上传出错
                    this.uploading = false;
                    this.$emit('error', err);
                },
                complete: () => { // 上传完成
                    const fileUrl = this.params.params.access_url;
                    this.$emit('input', fileUrl);
                    this.$emit('complete', this.params.params);
                    this.$refs.file.value = '';
                    this.uploading = false;
                    $ele.$message.success('上传成功');
                },
            };
            let file = '';
            if (e.target.files && e.target.files.length) file = e.target.files[0];
            // 创建上传实例
            const uploadVideo = new VideoUpload().observable(file, this.params.params);

            // 上传开始
            this.uploadVideo = uploadVideo.subscribe(observer);

            // 上传取消
            // subscription.unsubscribe();
        },
        // 上传取消
        unsubscribe() {
            if (this.uploadVideo) this.uploadVideo.unsubscribe();
            this.$refs.file.value = '';
            this.percentage = 0;
            this.uploading = false;
        },
        click() {
            this.$refs.file.click();
            // 获取上传参数
            this.params = new VideoUpload().getParams();
        },
    },
    mounted() {},
};
</script>

<style lang="scss">
    .video-upload {
        & > input {
            opacity: 0;
            position: absolute;
            left: 0;
            top: 0;
            width: 0;
            height: 0;
            padding: 0;
            margin: 0;
            z-index: -1;
            display: none;
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0)
        }
    }
</style>
